package com.spence.wsdemo.config;

import com.spence.wsdemo.interceptor.WsAuthHandshakeInterceptor;
import com.spence.wsdemo.interceptor.WsHandshakeHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

import javax.annotation.Resource;

/**
 * @author spence_xu
 * @date 2020/5/20 14:15
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    private final static String SOCKJS_URL = "https://cdn.bootcdn.net/ajax/libs/sockjs-client/1.4.0/sockjs.js" ;
    public final static String TOKEN_USER = "TokenUser" ;

    @Resource
    private WsAuthHandshakeInterceptor wsAuthHandshakeInterceptor;
    @Resource
    private WsHandshakeHandler wsHandshakeHandler;

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //订阅广播 Broker（消息代理）名称
        registry.enableSimpleBroker("/topic", "/queue", "/user");
        //全局使用的订阅前缀（客户端订阅路径上会体现出来）
        registry.setApplicationDestinationPrefixes("/ws/");
        //点对点使用的订阅前缀（客户端订阅路径上会体现出来），不设置的话，默认也是/user/
        registry.setUserDestinationPrefix("/user/");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws")
                .addInterceptors(wsAuthHandshakeInterceptor)
                .setHandshakeHandler(wsHandshakeHandler)
                .setAllowedOrigins("*")
                .withSockJS()
                .setClientLibraryUrl(SOCKJS_URL)
                .setSupressCors(true);
    }
}
